package com.spdzen.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spdzen.mapper.NewsCategoryMapper;
import com.spdzen.model.News;
import com.spdzen.model.NewsCategory;
import com.spdzen.service.NewsCategoryService;
import com.spdzen.service.NewsService;
import com.spdzen.support.SimpleServiceImpl;
import com.spdzen.support.exception.ResultCodeException;
import com.spdzen.support.result.BizResultCode;
import com.spdzen.support.result.ResultCode;
import com.spdzen.vo.NewsCategoryAdminVO;

/**
 * 新闻分类 服务实现类
 */
@Service("newsCategoryService")
public class NewsCategoryServiceImpl extends SimpleServiceImpl<NewsCategoryMapper, NewsCategory>
		implements NewsCategoryService {
	
	@Resource
	private NewsService newsService;

	@Transactional(rollbackFor = { Exception.class })
	@Override
	public void insertIfPermission(NewsCategory record) throws Exception {
		baseMapper.insert(record);

		NewsCategory entity = new NewsCategory();
		entity.setCode(record.getCode());
		if (selectCount(entity) > 1) {
			throw new ResultCodeException("分类编号已存在！");
		}
	}

	@Transactional(rollbackFor = { Exception.class })
	@Override
	public void updateIfPermission(NewsCategory record) throws Exception {
		baseMapper.updateById(record);

		NewsCategory entity = new NewsCategory();
		entity.setCode(record.getCode());
		if (selectCount(entity) > 1) {
			throw new ResultCodeException("分类编号已存在！");
		}
	}

	@Override
	public ResultCode deleteIfPermision(Long id) {
		NewsCategory entity = new NewsCategory();
		entity.setParentId(id);
		if (selectCount(entity) > 0) {
			return BizResultCode.error("分类下有子分类，不能删除！");
		}

		News record = new News();
		record.setNewsCategoryId(id);
		if(newsService.selectCount(record) > 0) {
			return BizResultCode.error("分类下有新闻，不能删除！");
		}
		
		baseMapper.deleteById(id);
		
		return BizResultCode.success();
	}
	
	@Override
	public NewsCategoryAdminVO selectOneAdminVO(Long id) {
		return baseMapper.selectOneAdminVO(id);
	}
	
	@Override
	public List<NewsCategoryAdminVO> selectAdminVO() {
		return baseMapper.selectAdminVO();
	}
}
